/* eslint-disable react/jsx-key */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin, Radio, Divider, Input} from 'antd';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import {injectIntl, language} from './intl';
import {getDetail} from './api';
import styles from './style.css';
import WrappedSelect from '../common/WrappedSelect';
import SearchInput from 'Shared/components/SearchInput';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import WrappedInputNumber from '../common/WrappedInputNumber';
import {gender, dealerType} from '../Enum';
import ProductSelectPanel from './ProductSelectPanel';
import WrappedDatePicker from '../common/WrappedDatePicker';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import TextInput from 'Shared/components/TextInput';
const genderList = gender.toList(language);
const dealerConditions = {
    type: dealerType.经销商
};
export class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        showProductSelectPanel: false,
        data: {},
        questionnaire: []
    };

    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data
                    });
                this.setState({
                    loading: false
                });
            });
    }

    componentWillUnmount() {
        this.isunmount = true;
    }

    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    
    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onSubmit = () => {
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickSearchProductBtn = id => {
        this.setState({
            detailId: id,
            showProductSelectPanel: true
        });
    }
    onClickAddProductDetailBtn = () => {
        this.setState({
            showProductSelectPanel: !this.state.showProductSelectPanel
        });
    }
    onSelectProduct = records => {
        const tmp = Object.assign({}, this.state.data, {
            productCategoryId: records.id,
            productCategoryName: records.name,
        });
        this.setState({
            data: tmp,
            hasOperat: true,
            showProductSelectPanel: false
        });
    }
    onChangScore = (e, i) => {
        const {id, value} = e.target;
        const questionnaire = this.state.questionnaire;
        const newDetail = questionnaire.find(p => p.serviceSurveyQuestionId === id) || {};
        const tmp = Object.assign({}, newDetail, {
            score: value,
        });
        if(value < 7) {
            tmp.showName = true;
            questionnaire.splice(i, 1, tmp);
            return this.setState({
                questionnaire,
                hasOperat: true
            });
        }
        tmp.showName = false;
        questionnaire.splice(i, 1, tmp);
        this.setState({
            questionnaire,
            hasOperat: true
        });
    }
    onChangeName = (e, score, did, i) => {
        const {id} = e.target;
        const details = this.state.details.filter(p => p.serviceSurveyQuestionId !== did) || {};
        const tmp = {
            serviceSurveyQuestionId: did,
            score,
            extraDetails: [{
                serviceSurveyQuestionDetailId: id,
            }]
        };
        details.push(tmp);
        this.setState({
            details,
            hasOperat: true
        });
    }
    changeRemark = (e, id, did) => {
        const details = this.state.details.filter(p => p.serviceSurveyQuestionId !== id) || [];
        const newDetail = this.state.details.find(p => p.serviceSurveyQuestionId === id) || {};
        const tmp = {
            ...newDetail,
            extraDetails: [{
                serviceSurveyQuestionDetailId: did,
                remark: e.target.value
            }]
        };
        details.push(tmp);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {data} = this.state;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const validateAmount = !data.amount && this.state.validate ? 'error' : null;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        const number = [
            {
                score: '1',
                color: '#fffbe6'
            },
            {
                score: '2',
                color: '#ffffb8'
            },
            {
                score: '3',
                color: '#fffb8f'
            },
            {
                score: '4',
                color: '#fff566'
            },
            {
                score: '5',
                color: '#ffec3d'
            },
            {
                score: '6',
                color: '#fadb14'
            },
            {
                score: '7',
                color: '#d4b106'
            },
            {
                score: '8',
                color: '#ad8b00'
            },
            {
                score: '9',
                color: '#876800'
            },
            {
                score: '10',
                color: '#614700'
            },
        ];
        const radioStyle = {
            display: 'block',
            height: '30px',
            lineHeight: '30px',
        };
        const dealerInfo = data.subDealerId ? {
            id: data.subDealerId,
            code: data.subDealerCode,
            name: data.subDealerName
        } : null;
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'updatePanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.text.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item} required>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.city',
                                        defaultMessage: '城市'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.city}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.subDealerCode',
                                        defaultMessage: '经销商'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.subDealerCode && this.state.validate ? 'error' : null}
                                    required>
                                        <DealerSelectPanel
                                            value={dealerInfo}
                                            conditions={dealerConditions}
                                            onSelect={this.onSelectSubDealer} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.productCategoryId',
                                        defaultMessage: '车型'
                                    })}{...FORM_OPTIONS.item} validateStatus={!data.productCategoryId && this.state.validate ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.productCategoryName}
                                            onClickSearchBtn={() => this.onClickSearchProductBtn(data.id)} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.mileage',
                                        defaultMessage: '行驶里程'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.mileage && this.state.validate ? 'error' : null}
                                    required>
                                        <LocalizeInputNumber
                                            name="mileage"
                                            value={data.mileage}
                                            max={1000000000}
                                            min={0}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.name',
                                        defaultMessage: '客户姓名'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.customerName && this.state.validate ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="customerName"
                                            value={data.customerName}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.saleDate',
                                        defaultMessage: '购车日期'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.saleDate && this.state.validate ? 'error' : null}
                                    required>
                                        <WrappedDatePicker
                                            name="saleDate"
                                            value={data.saleDate}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.gender',
                                        defaultMessage: '客户性别'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.gender && this.state.validate ? 'error' : null}
                                    required>
                                        <WrappedSelect
                                            name="gender"
                                            value={data.gender}
                                            options={genderList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.contactNumber && this.state.validate ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="contactNumber"
                                            value={data.contactNumber}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.age',
                                        defaultMessage: '年龄'
                                    })} {...FORM_OPTIONS.item}
                                    validateStatus={!data.age && this.state.validate ? 'error' : null}
                                    required>
                                        <WrappedInputNumber
                                            name="age"
                                            min={0}
                                            precision={0}
                                            value={data.age}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        {<Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'updatePanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>}
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.detail',
                            defaultMessage: '问题清单'
                        })}>
                            {this.state.questionnaire ? this.state.questionnaire.map((v, i) => <div><Row>
                                <Radio.Group onChange={e => this.onChangScore(e, i)} buttonStyle="solid">
                                    {
                                        number.map((v1, i1) =>
                                            <Radio.Button id={v.serviceSurveyQuestionId} value={i1 + 1} key={i1 + 1}>{v1.score}</Radio.Button>
                                        )
                                    }
                                </Radio.Group></Row>
                            <Row>
                                {
                                    v.showName && <Radio.Group onChange={e => this.onChangeName(e, v.score, v.serviceSurveyQuestionId, i)}>
                                        {
                                            v.extraDetails.map((v2, i2) =>
                                                <div style={{display: 'flex',
                                                    marginTop: 10}}><Radio value={i2 + 1} id={v2.serviceSurveyQuestionDetailId}>
                                                        {`${i + 1}.${i2 + 1}：${v2.optionName}`}
                                                    </Radio>：<Input name="remark" onChange={e => this.changeRemark(e, v.serviceSurveyQuestionId, v2.serviceSurveyQuestionDetailId)} style={{marginLeft: 10}} /></div>
                                            )
                                        }
                                            其他：<Input name="others" style={{marginLeft: 10}} />
                                    </Radio.Group>
                                }
                            </Row>
                            <Divider className={styles.divider}/>
                            </div>) : null}
                        </Card>
                    </Form>
                    {
                        this.state.showProductSelectPanel && <ProductSelectPanel
                            onCancel={this.onClickAddProductDetailBtn}
                            onSelect={this.onSelectProduct} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onSubmit(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url())
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
